package com.sc.sysconfig.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sc.sysconfig.dto.RoleQueryDTO;
import com.sc.sysconfig.entity.SysRole;
import com.sc.sysconfig.entity.SysRoleMenu;
import com.sc.sysconfig.service.SysRoleMenuService;
import com.sc.sysconfig.service.SysRoleService;
import com.sc.sysconfig.vo.OptionVO;
import com.sc.sysconfig.vo.PageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * 系统角色控制器
 *
 * @author 徐赫阳
 * @date 2021/09/13
 */
@Api(description = "角色")
@RestController
@RequestMapping("/role")
public class SysRoleController {
    /**
     * 服务对象
     */
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @ApiOperation("分页获取角色")
    @PostMapping("/getRoleList")
    public PageVO<SysRole> getRoleList(@RequestBody RoleQueryDTO queryDTO){
        return sysRoleService.getRoleList(queryDTO);
    }

    @ApiOperation("根据id获取角色")
    @GetMapping("/getRoleById/{id}")
    public SysRole getRoleById(@PathVariable Integer id){
        return sysRoleService.getById(id);
    }

    @ApiOperation("保存角色")
    @PostMapping("/saveRole")
    @Transactional(propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public Integer saveRole(@RequestBody SysRole sysRole, HttpServletRequest request){
        if(sysRole.getId() == null){
            sysRole.setCreatorId((Integer)request.getSession(true).getAttribute("user"));
        }else{
            sysRole.setUpdaterId((Integer)request.getSession(true).getAttribute("user"));
        }
        sysRoleService.saveOrUpdate(sysRole);
        List<Integer> permissions = sysRole.getPermission();
        Integer roleId = sysRole.getId();
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRoleMenu::getRoleId,roleId);
        sysRoleMenuService.remove(queryWrapper);
        for(Integer i:permissions){
            sysRoleMenuService.save(new SysRoleMenu(roleId,i));
        }
        return sysRole.getId();
    }

    @ApiOperation("获取角色下拉列表")
    @GetMapping(value = "/getRoleOption")
    public List<OptionVO> getRoleOption(){
        return sysRoleService.getRoleOption();
    }

    @ApiOperation("获取全部角色")
    @GetMapping(value = "/getAllRole")
    public List<OptionVO> getAllRoles(){
        return sysRoleService.getAllRole();
    }

    @ApiOperation("删除")
    @DeleteMapping(value = "/deleteRole/{id}")
    public void deleteRole(@PathVariable Integer id) throws Exception{
        sysRoleService.removeById(id);
    }

}
